﻿var popupDoc = null;
var resultsDoc = null;
var storage = window.localStorage;
var resultsTab = null;
var spiderTab = null;
var RESULTS_TITLE = 'iMonkey';
var spiderTimeout = 0;
var metricsInterval = 0;

var urlTodo = [];
var urlDone = [];
var mid = null;

function popupLoaded(doc) {
  popupDoc = doc;
  chrome.tabs.getSelected(null, setDefault);
}

function setDefault(tab) {
	if (storage.url) {
		$(popupDoc).find('#url').val(storage.url);
	}
}

function recordDefault() {
  storage.url = $(popupDoc).find('#url').val();
}

function popupGo() {
	
	recordDefault();
  popupStop();

	urlTodo[storage.url] = true;
	
	function resultsLoadCallback_(tab) {
    resultsTab = tab;
    resultsDoc = getResultsDoc();
		setStatus('任务开始.....');
		startRun();

		metricsInterval = window.setInterval(healthCheck, 10 * 1000);

  }
  chrome.tabs.create({url: 'results.html'}, resultsLoadCallback_);
}

function healthCheck() {
	if (lst_metrics != metrics) {
		lst_metrics = metrics;
		return ;
	} else {
		setStatus('健康检测到任务暂停，重新启动');
		startRun();
	}
}

function popupStop() {	 
	var resultsWindows = chrome.extension.getViews({type: 'tab'});
  for (var x = 0; x < resultsWindows.length; x++) {
    var doc = resultsWindows[x].document;
    if (doc.title == RESULTS_TITLE) {
      doc.title = '【已结束】';
    }
  }

	urlTodo = [];
	urlDone = [];
	if (spiderTab){
		chrome.tabs.remove(spiderTab.id);
		spiderTab = null;
	}
	
  resultsTab = null;
	window.clearInterval(metricsInterval);
	window.clearTimeout(spiderTimeout);
}

function setStatus(msg) {
	msg = (new Date()).Format("hh:mm:ss") + ' - ' +  msg;
	$(resultsDoc).find('#log').append(msg+"\n");
}

function setContent(msg) {
	$(resultsDoc).find('#results').append(msg+"\n");
}


function getResultsDoc() {
  var resultsWindows = chrome.extension.getViews({type: 'tab'});
  for (var x = 0; x < resultsWindows.length; x++) {
    var doc = resultsWindows[x].document;
    if (doc.title == RESULTS_TITLE) {
      return doc;
    }
  }
  popupStop();
  return null;
}

function startRun() {
	
	var url;
	for ( url in urlTodo ){
			break;
	}

	mid = urlTodo[url];

	delete urlTodo[url];
	urlDone[url] = true;

	if (url) {
		setStatus('抓取'+url);
		
		chrome.tabs.create({url: url, selected:false} , function (tab){
				if (spiderTab){
					chrome.tabs.remove(spiderTab.id);
					spiderTab = null;
				}
				spiderTab = tab;

				chrome.tabs.executeScript(spiderTab.id, {file: 'inject.js'} , function() {
					;
				});
		});

	} else {
		
		popupStop();
		setStatus('运行结束');
		return;
	
	}
}

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
	if (request.action == 'data') {
			for(var i=0; i<request.page.length; i++)
			{
					var link = request.page[i]; 
					if ( link && ! urlTodo[link] && ! urlDone[link] )
					{
						urlTodo[link] = true;
					}
			}
						
			for(var i=0; i<request.content.length; i++)		{
					setContent( request.content[i] );
			}

			for(var i=0; i<request.comment.length; i++)		{
					
					var link = request.comment[i][1]; 
					if ( link && ! urlTodo[link] && ! urlDone[link] )
					{
						urlTodo[link] = request.comment[i][0];
					}

			}

			spiderTimeout = window.setTimeout(startRun, 100);
	}

	if (request.action == 'comment') {
		
		for(var i=0; i<request.comment.length; i++)		{

			var match = request.comment[i].match(/(.*?)\((.*?)\)/);
			var main = match[1];
			var date = match[2];

			setContent( mid + '||comment||' + main + '||'+date );
		}

		spiderTimeout = window.setTimeout(startRun, 100);
	
	}
});